package com.chanyachting.emall.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.upload.FormFile;

public class MyFile {
	
	
	public static boolean writeFile(String filePath,String context){
		
		File file=new File(filePath);
		
		if(file.exists()){
			
			 try {
				OutputStreamWriter  writer = new OutputStreamWriter (new FileOutputStream(file),"UTF-8");
				
				writer.write(context);
				
				writer.close();
				
				return true;
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		return false;
		
	}
	
	
	public static String readeFile(String filePath){
		
		File file=new File(filePath);
		
		if(file.exists()){
			
			try {
				InputStreamReader reader=new InputStreamReader(new FileInputStream(file),"UTF-8");
				
				BufferedReader br = new BufferedReader (reader);

	            String s;
	            
	            StringBuffer string=new StringBuffer();

	             while ((s = br.readLine() )!=null) {

	                string.append(s+"\n");

	              }

	            br.close();
	             
	            reader.close();
	            
	            return string.toString();
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return null;
	}
	
	
	
	public static String saveFileForm(FormFile myFile,HttpServletRequest request){
		
		RequestUtil ru=new RequestUtil(request);
		
		String returnString="";
		
		 if(myFile!=null){

	          try {
	        	  
	        	  String uploadPath=ru.getDefUploadPath();
	        	  
	        	  String myFileName=myFile.getFileName();  //获得文件名
	        	  
	        	 //保存文件操作
	             FileOutputStream fos = new FileOutputStream(uploadPath+myFileName);

	             fos.write(myFile.getFileData());

	             fos.flush();

	             fos.close();
	             
	             //文件保存成功，返回文件web访问地址
	             returnString=ru.getDefWebUrl(myFileName);

	          } catch (Exception e) {

	             //e.printStackTrace();
	        	  
	        	  return null;

	          }

	      }
		
		return returnString;
	}

}
